package cmich.cps.scheduler;

import java.io.File;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
import java.util.logging.SimpleFormatter;

/**
 * The Class MyLogger.
 * 
 * @author Jonathan Kissinger <kissi1j@cmich.edu>
 */
public class MyLogger {
	
	/** The logging indicator. */
	private static Boolean logging = false;

	/**
	 * Setup the logger.
	 *
	 * @param trigger the trigger level
	 * @param level the level
	 */
	static public void setup(final Level trigger, Level level, File dir) {
		String basePackage = MyLogger.class.getPackage().getName().split("\\.")[0];
		Logger logger = Logger.getLogger(basePackage);
		logger.setLevel(level);
		try {
			File logDir = new File(dir + File.separator + "logs");
			if(!logDir.exists()) {
				logDir.mkdir();
			}
			File logFile = new File(logDir + File.separator + "Log.txt");
			SimpleFormatter simple = new SimpleFormatter();

			if(trigger.intValue()>Level.FINEST.intValue()) {
				FileHandler fileHandler = new FileHandler(logFile.getAbsolutePath(), 2097152, 10, true);
				fileHandler.setFormatter(simple);
				int numRec = 100;
				MemoryHandler logMemory = new MemoryHandler(fileHandler, numRec, Level.OFF) {
					public synchronized void publish(LogRecord record) {
						super.publish(record);

						if(logging) {
							push();
						}
						else if (record.getLevel().intValue()>=trigger.intValue()) {
							logging=true;
							push();
						}                           
					}
				};
				logMemory.setFormatter(simple);
				logger.addHandler(logMemory);
			}
			else {
				//Prevents info and higher from printing to the screen twice
				Logger.getLogger("").getHandlers()[0].setLevel(Level.OFF);

				ConsoleHandler console = new ConsoleHandler();
				console.setFormatter(simple);
				console.setLevel(level);
				logger.addHandler(console);
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
